package com.yfunc.common.command;

import java.util.HashSet;
import java.util.Set;

import com.yfunc.common.command.handlers.AnnotationCommandHandler;

public class DefaultCommandBus implements CommandBus {
	
	private Set<CommandHandler> handles;
	
	public DefaultCommandBus(){
		this.handles = new HashSet<CommandHandler>();
	}

	@Override
	public Command execute(Command command) {
		if( command == null) {
			throw new IllegalArgumentException("published null command!");
		}
		return this.executeCommand(command);
	}

	@Override
	public void register(CommandHandler handler) {
		if (handler == null) {
			throw new IllegalArgumentException("register null handler!");
		}
		this.handles.add(handler);
	}

	@Override
	public void register(Object handler) {
		if (handler == null) {
			throw new IllegalArgumentException("register null handler!");
		}
		this.register(new AnnotationCommandHandler(handler)) ;
	}
	
	private Command executeCommand(Command command) {
		CommandHandler[] commandHandlers = handles.toArray( new CommandHandler[0]) ;		
		for (CommandHandler handle : commandHandlers) {
			if (handle.isSupported(command)) {
				 return handle.execute(command);
			}
		}	
		return null;
	}

}
